import { Component, ViewChild } from '@angular/core';
import { Events, AlertController, App, ModalController, NavController, Content } from 'ionic-angular';
import { TaskListService } from './list.service';
import { Config } from '../../../providers/config';
import { TaskDetailPage } from '../detail/detail.component';
import { TaskDetailService } from '../detail/detail.service';
import { InfoDetailPage } from '../../../pages/info/detail/detail.component';

import _ from 'lodash';
import {DraftDetailPage} from "../../draft/detail/detail.component";
import {Common} from "../../../providers/common";

@Component({
  selector: 'page-task-list',
  templateUrl: './list.html',
  providers: [TaskListService, TaskDetailService]
})
export class TaskListPage {
	moa_page_name: any = "page-task-list";
  moa_page_explain: any = "待办中心(待办)";

  // 列表数据
  listData: any = {};

  @ViewChild(Content) content: Content;

  segment = 'toBeDeal';
  // 用来记录切换之前的
  currentSegment = 'toBeDeal';
  // 1-所有待办 2- 所有未办   3- 所有已办 4-所有未阅 5-所有已阅
  segments = [{
    name: 'toBeDeal',
    text: '待办',
    wkiType: '1'
  }, {
    name: 'todo',
    text: '未办',
    wkiType: '2'
  }, {
    name: 'deal',
    text: '已办',
    wkiType: '3'
  }, {
    name: 'toBeRead',
    text: '未阅',
    wkiType: '4'
  }, {
    name: 'read',
    text: '已阅',
    wkiType: '5'
  }];

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public taskListService: TaskListService,
    public taskDetailService: TaskDetailService,
    public config: Config,
    public events: Events,
    private common: Common
  ) {
    let that = this;
    _.each(this.segments, function(item, index) {
      that.listData[item.name] = {
        pageIndex: 1,
        data: [],
        scrollTop: 0,
        isLoadMore: true,
        wkiType: item.wkiType,
        needReflash: false  // 标记是否需要刷新
      };
    });

    // 初始化数据
    this.loadListData(this.segment, this.listData[this.segment].wkiType, 1, true, null, null);

    // 先注销监听，防止启动多次
    this.events.unsubscribe("task-detail:read"); // 更新已阅
    this.events.unsubscribe("task-detail:toBeDeal,todo,deal has updated"); // 更新已办
    this.events.unsubscribe("task-detail: take back"); // 收回

    //启动监听， 如果有未阅读被点击打开，则将未阅更新成已阅，更新已阅列表
    this.events.subscribe("task-detail:read", data => {
      console.log("###监听到task-detail:read:")
      if (this.segment == "read") { // 如果当前处在已阅列表，则马上刷新
        this.doRefreshWithSegment("read", null, false);
      } else { // 如果当前处不在已阅列表，则标记为需要刷新，当切换到已阅列表时再刷，主要为了提高用户体验减少接口请求次数
        this.listData["read"].needReflash = true;
      }
    });
    // 启动监听，流程有更新操作，刷新待办、未办、已办列表
    this.events.subscribe("task-detail:toBeDeal,todo,deal has updated", data => {
      console.log("###监听到task-detail:toBeDeal,todo,deal has updated:")
      // 移除待办列表指定bid对象
      //this.doRefreshWithSegment("toBeDeal",null,false);
      _.pull(this.listData["toBeDeal"].data, _.find(this.listData["toBeDeal"].data, { "bid": data.bid }));
      //如果未办列表有数据，移除未办列表指定bid对象
      _.pull(this.listData["todo"].data, _.find(this.listData["todo"].data, { "bid": data.bid }));
      //this.doRefreshWithSegment("todo",null,false);
      // 刷新已办列表
      if (this.segment == "deal") {
        this.doRefreshWithSegment("deal", null, false);
      } else {
        this.listData["deal"].needReflash = true;
      }
    });

    //启动监听， 如果有收回，更新未办列表、已办列表
    this.events.subscribe("task-detail: take back", data => {
      console.log("###监听到task-detail: take back:")
      _.pull(this.listData["deal"].data, _.find(this.listData["deal"].data, { "bid": data.bid }));
      this.listData["toBeDeal"].needReflash = true;
      this.listData["todo"].needReflash = true;
    });

  }
  /**
   * [loadListData 加载列表数据]
   * @param {[type]} type           [类型]
   * @param {[type]} page           [页码]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(segment, type, page, isShowLoading, infiniteScroll, refresher) {
    this.taskListService.getListData(page, type, isShowLoading).subscribe(data => {
      console.log(data);
      if (data) {
        //console.info(data);
        // 如果加载第一页，则清空数据
        if (page == 1) {
          this.listData[segment].isLoadMore = true;
          this.listData[segment].data = [];
        }
        // 把现有数据和新加载的数据合并
        this.listData[segment].data = _.concat(this.listData[segment].data, data);
        // 增加搜索索引
        this.listData[segment].pageIndex = this.listData[segment].pageIndex + 1;
        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.listData[segment].isLoadMore = false;
        }
      } else {
        this.listData[segment].isLoadMore = false; // 返回null,当做没有更多数据
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  };

  onSegmentChange(segmentEvent) {
    this.listData[this.currentSegment].scrollTop = this.content.scrollTop;
    // 当数据未加载，或者需要刷新
    if (this.listData[this.segment].pageIndex === 1 || this.listData[this.segment].needReflash) {
      this.loadListData(this.segment, this.listData[this.segment].wkiType, 1, true, null, null);
      this.listData[this.segment].needReflash = false; // 刷新后，重置
    }

    this.content.scrollTo(0, this.listData[this.segment].scrollTop, 1);
    this.currentSegment = this.segment;

    switch (this.segment) {
      case "toBeDeal":
        this.common.saveUserStatistics(this.moa_page_name, this.moa_page_name + "-" + this.segment, "待办中心(待办)");
        break;
      case "todo":
        this.common.saveUserStatistics(this.moa_page_name, this.moa_page_name + "-" + this.segment, "待办中心(未办)");
        break;
      case "deal":
        this.common.saveUserStatistics(this.moa_page_name, this.moa_page_name + "-" + this.segment, "待办中心(已办)");
        break;
      case "toBeRead":
        this.common.saveUserStatistics(this.moa_page_name, this.moa_page_name + "-" + this.segment, "待办中心(未阅)");
        break;
      case "read":
        this.common.saveUserStatistics(this.moa_page_name, this.moa_page_name + "-" + this.segment, "待办中心(已阅)");
        break;
    }
  };
  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
  goDetailPage(item) {
    console.log(item);
    //通知公告页面针对待办和送阅的处理方式是，判断sreserved3的状态，如果sreserved3不等于5或者7，
    //那么就表示这是一个待办（未发布）；如果为5或者7，那么表示这是一个送阅（已发布）
    if (item.bomid == "t_info_Doc") {
      this.taskListService.selectAllInfo(item.bid).subscribe(data => {
        console.log("信息中心 - selectAllInfo", data);
        if (_.indexOf(["5"], data.sreserved3) > -1) { // 已发布，跳转到通知公告详情页面
          // 未阅，点击后变成已阅,在列表中移除
          if (item.wkiState == "8") {
            _.pull(this.listData["toBeDeal"].data, _.find(this.listData["toBeDeal"].data, { "bid": item.bid }));
            _.pull(this.listData["toBeRead"].data, _.find(this.listData["toBeRead"].data, { "bid": item.bid }));

            // 更新成已阅状态
            this.taskDetailService.workitemAsRead(item["flownumb"]).subscribe(data => {
              if (data["code"] == "0") {
                console.log("##task.detail.loadData 已更新成已阅状态");
                this.events.publish('task-detail:read', item.bid); // 广播,让已阅列表刷新
              } else {
                console.log("##task.detail.loadData 已阅状态更新失败");
                console.log(data);
              }
            })
          }
          this.navCtrl.push(InfoDetailPage, { fbbosid: item.bid, isRemote: "true" });
        } else {
          this.navCtrl.push(TaskDetailPage, { id: item.bid, wkiType: this.listData[this.segment].wkiType, wkiState: item.wkiState });
          // this.goNTKO(item);
        }
      })
    } else {
      if (item.wkiState == "8") { // 点击后变成已阅,在列表中移除
        _.pull(this.listData["toBeDeal"].data, _.find(this.listData["toBeDeal"].data, { "bid": item.bid }));
        _.pull(this.listData["toBeRead"].data, _.find(this.listData["toBeRead"].data, { "bid": item.bid }));
      }

      if (this.config.allowDraftFlow.indexOf(item.bomid) > -1 && (item.wkiName === "起始节点"
        || item.wkiName.indexOf("起草") > -1)) {
        this.taskListService.selectAllInfo(item.bid).subscribe(data => {
          console.log("selectAllInfo().data", data);
          if (data && data.sreserved3) {
            if (data.sreserved3 === "" || data.sreserved3 === "8" || data.sreserved3 === "7") {
              this.goDraftEditPage(item);
            } else {
              this.navCtrl.push(TaskDetailPage,{id: item.bid, wkiType: "2", wkiState: item.wkiState});
            }
          } else {
            this.goDraftEditPage(item);
          }
        });
      } else {
        this.navCtrl.push(TaskDetailPage,{id: item.bid, wkiType: "2", wkiState: item.wkiState});
      }

      // this.navCtrl.push(TaskDetailPage, { id: item.bid, wkiType: this.listData[this.segment].wkiType, wkiState: item.wkiState });
    }
  };

  /**
   * [goNTKO 发文正文详情页面]
   * @param {[type]} item [description]
   */
  goNTKO(item){
    this.navCtrl.push(InfoDetailPage, {
      "isRemote": "true", // 如果是信息中心则为true,反之 false
      "fbbosid": item.bid,
      "isNotShowOrgnameAndBosdate": false
    });
  }

  goDraftEditPage(item) {
    let type = "";
    switch (item.bomid) {
      case "T_HR_ChuChai":
        type = "ccsq";
        break;
      case "T_HR_ChuJingSQ":
        type = "cjsq";
        break;
      case "T_HR_ChuQinBG":
        type = "cqbg";
        break;
      case "T_HR_GongWuWC":
        type = "gwwc";
        break;
      case "T_HR_QingJia":
        type = "qxjsq";
        break;
    }

    this.navCtrl.push(DraftDetailPage, {
      ops: "reject",
      bosid: item.bid,
      type : type
    });
  }

  ionViewDidLoad() {

  };
  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll, isShowLoading) {
    if (this.listData[this.segment].isLoadMore) {
      this.loadListData(this.segment, this.listData[this.segment].wkiType, this.listData[this.segment].pageIndex, isShowLoading, infiniteScroll, null);
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher, isShowLoading) {
    this.listData[this.segment].pageIndex = 1;
    this.listData[this.segment].isLoadMore = true;
    this.loadListData(this.segment, this.listData[this.segment].wkiType, this.listData[this.segment].pageIndex, isShowLoading, null, refresher);
  }

    /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefreshWithSegment(segment, refresher, isShowLoading) {
    this.listData[segment].pageIndex = 1;
    this.listData[segment].isLoadMore = true;
    this.loadListData(segment, this.listData[segment].wkiType, this.listData[segment].pageIndex, isShowLoading, null, refresher);
  }


}
